module(..., package.seeall)


config      = package.config:split("\n")
path_sep    = config[1]
entry_sep   = config[2]
placeholder = config[3]
patterns    = {placeholder .. ".lua",
               placeholder .. ".luac",
               placeholder .. path_sep .. "init.lua"}
               
entries = set()  -- set of path entries (used to avoid repetition, hence a set instead of a list)
for _, entry in ipairs(package.path:split(entry_sep)) do
    entries:add(entry)
end

function package.add_lua_path(directory)
    if directory:sub(-#path_sep) ~= path_sep then
        directory = directory .. path_sep
    end
    local parts = {package.path}
    for _, pattern in ipairs(patterns) do
        local entry = directory .. pattern
        if not entries:contains(entry) then
            entries:add(entry)
            table.insert(parts, entry_sep)
            table.insert(parts, entry)
        end
    end
    package.path = table.concat(parts)
end

function package.show_lua_path()
    print("Search path for Lua modules:")
    for i, entry in ipairs(package.path:split(entry_sep)) do
        print(i, entry)
    end
end

package.add_lua_path(".")
package.show_lua_path()
